# ==== hazard_detection.py ====
class HazardDetection:
    @staticmethod
    def detect_data_hazard(id_ex, if_id):
        """检测加载使用冒险"""
        if not if_id.valid or not id_ex.valid:
            return False

        # 只有加载指令会导致冒险
        if id_ex.control_signals["MemRead"]:
            # 解析当前指令的源寄存器
            opcode = (if_id.instruction >> 26) & 0x3F
            rs = (if_id.instruction >> 21) & 0x1F
            rt = (if_id.instruction >> 16) & 0x1F

            # 检查是否与加载指令的目标寄存器冲突
            if (id_ex.write_reg == rs) or (id_ex.write_reg == rt):
                return True

        return False

    @staticmethod
    def detect_control_hazard(ex_mem):
        return ex_mem.valid and ex_mem.control_signals["Branch"] and ex_mem.zero